package com.codingbee.service;

import com.codingbee.config.ExpirationMessagePostProcessor;
import com.codingbee.util.Const;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Description 订单相关业务
 * @Author zouxiang
 * @Date 2020/4/3/22:57
 */
@Service
@Slf4j
public class OrderService {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 模拟下单操作
     *
     * @return
     */
    public String placeOrder() {
        //LocalDateTime localDateTime = LocalDateTime.now();
        // 模拟下单逻辑，返回订单号，将订单号存在redis中，并且发送到死信队列，当死信队列到期了将redis的订单号删掉
        long l = System.currentTimeMillis();
        log.info(String.format("【%s】收到下单请求，订单号为:[%s]", new Date(), l));
        rabbitTemplate.convertAndSend("", Const.DELAY_QUEUE_PER_QUEUE_TTL_NAME, l, new ExpirationMessagePostProcessor(Const.PAY_TIME_OUT * 1000L * 60L));
        redisTemplate.opsForValue().set(String.valueOf(l), String.valueOf(l));
        return String.valueOf(l);
    }

    /**
     * 删除逾期未支付的订单
     */
    @RabbitListener(queues = "delayProcess")
    public void delDelayOrder(String l) {
        log.info("收到要删除的订单号为：" + l);
        redisTemplate.delete(String.valueOf(l));    //将订单从redis删除
    }

    /**
     * 模拟支付订单操作
     */
    public String payOrder(String orderNo) {
        log.info(String.format("收到要支付的订单号为：【%s】", orderNo));
        if (redisTemplate.hasKey(orderNo)){
            redisTemplate.delete(orderNo);
            return String.format("订单号【%s】的订单支付成功。",orderNo);
        }else{
            return String.format("订单号【%s】的订单已经超过支付时间，请重新下单。",orderNo);
        }
    }
}
